﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace CustomControlLib.TextBoxs
{
    public class WatermarkedTextBox : TextBox
    {
        // 定义 Watermark 依赖属性
        public static readonly DependencyProperty WatermarkProperty =
            DependencyProperty.Register("Watermark", typeof(string), typeof(WatermarkedTextBox),
                new PropertyMetadata(default(string)));

        public string Watermark
        {
            get { return (string)GetValue(WatermarkProperty); }
            set { SetValue(WatermarkProperty, value); }
        }

        // 定义 IsWatermarkVisible 依赖属性
        private static readonly DependencyPropertyKey IsWatermarkVisiblePropertyKey =
            DependencyProperty.RegisterReadOnly("IsWatermarkVisible", typeof(bool), typeof(WatermarkedTextBox),
                new PropertyMetadata(false));

        public static readonly DependencyProperty IsWatermarkVisibleProperty = IsWatermarkVisiblePropertyKey.DependencyProperty;

        public bool IsWatermarkVisible
        {
            get { return (bool)GetValue(IsWatermarkVisibleProperty); }
            private set { SetValue(IsWatermarkVisiblePropertyKey, value); }
        }

        public WatermarkedTextBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkedTextBox),
                new FrameworkPropertyMetadata(typeof(WatermarkedTextBox)));
        }

        // 重写 OnTextChanged 方法，以更新 IsWatermarkVisible 属性
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            base.OnTextChanged(e);
            UpdateWatermarkVisibility();
        }

        // 更新水印可见性
        private void UpdateWatermarkVisibility()
        {
            IsWatermarkVisible = string.IsNullOrWhiteSpace(Text);
        }
        // 重写 OnGotFocus 和 OnLostFocus 方法，以处理焦点变化
        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);
            IsWatermarkVisible = false;
        }
        protected override void OnLostFocus(RoutedEventArgs e)
        {
            base.OnLostFocus(e);
            UpdateWatermarkVisibility();
        }
    }
}
